<template>
  <div class="icon-select">
    <el-input
      v-model="currentIcon"
      placeholder="点击选择图标"
      readonly
      @click="showDialog"
    >
      <template #prefix>
        <el-icon v-if="currentIcon">
          <component :is="currentIcon" />
        </el-icon>
      </template>
    </el-input>

    <el-dialog
      v-model="dialogVisible"
      title="选择图标"
      width="800px"
    >
      <div class="icon-list">
        <div
          v-for="icon in icons"
          :key="icon"
          class="icon-item"
          @click="selectIcon(icon)"
        >
          <el-icon>
            <component :is="icon" />
          </el-icon>
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import * as ElementPlusIcons from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: String
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = ref(false)
const currentIcon = ref(props.modelValue)

// 获取所有Element Plus图标
const icons = Object.keys(ElementPlusIcons)

// 选择图标
const selectIcon = (icon) => {
  currentIcon.value = icon
  emit('update:modelValue', icon)
  dialogVisible.value = false
}

// 显示对话框
const showDialog = () => {
  dialogVisible.value = true
}

// 监听父组件传入的值变化
watch(() => props.modelValue, (newVal) => {
  currentIcon.value = newVal
})
</script>

<style scoped>
.icon-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  padding: 16px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.icon-name {
  margin-top: 8px;
  font-size: 12px;
}

.icon-select .el-input__prefix {
  font-size: 16px;
}
</style>